// import request from 'app/utils/request'

interface IWindow {
  SYNC_HANDLE: any
}

const iWindow: IWindow = {
  SYNC_HANDLE: null
}

/**
 * 编辑器操作缓存类
 */
class OperationCache {
  static CACHE_KEY = 'v:display:operation:history'
  static MAX_HISTORY = 500
  static SYNC_TIME = 2000
  static SYNC_HANDLE = null

  /**
   * 压入队列
   *
   * @param operation
   */
  public static push = (operation) => {
    const operationRecord =
      localStorage.getItem(OperationCache.CACHE_KEY) || '[]'
    const records = JSON.parse(operationRecord)
    records.push({ isSync: false, operation })
    localStorage.setItem(
      OperationCache.CACHE_KEY,
      JSON.stringify(records.slice(-OperationCache.MAX_HISTORY))
    )
  }

  /**
   * 撤销操作
   */
  public static undo = () => {
    const operationRecord =
      localStorage.getItem(OperationCache.CACHE_KEY) || '[]'
    const records = JSON.parse(operationRecord)
    const record = records.pop()
    // 已同步到服务端, 则将上一条记录覆盖到服务端
    if (record.isSync) {
      const prevRecord = records.length > 0 ? records.slice(-1).pop() : null
      // 同步到服务端
      if (prevRecord) {
        OperationCache.sendToServer(prevRecord.operation)
      }
    }
    localStorage.setItem(
      OperationCache.CACHE_KEY,
      JSON.stringify(records.slice(-OperationCache.MAX_HISTORY))
    )
  }

  /**
   * 上报数据到服务器
   *
   * @param operation
   */
  public static sendToServer = (operation) => {
    // request(operation.url, operation)
  }

  /**
   * 持久化操作结果
   */
  public static saveToServer = () => {
    const operationRecord =
      localStorage.getItem(OperationCache.CACHE_KEY) || '[]'
    const records = JSON.parse(operationRecord)
    const waitSyncRecords = records.filter((item) => !item.isSync)
    // 同地址接口取最后一条记录同步
    const needSyncRecords = Array.from(
      new Set(waitSyncRecords.map((item) => item.operation.url))
    )
    needSyncRecords.forEach((url) => {
      const syncRecords = waitSyncRecords.filter(
        (item) => item.operation.url == url
      )
      // 最后一条记录同步到服务器
      const record = syncRecords.pop()
      OperationCache.sendToServer(record.operation)
      records.forEach((item) => {
        if (!item.isSync && item.operation.url == url) {
          item.isSync = true
        }
      })
    })
    // 要考虑写冲突问题，如在自动同步过程中，同时也在编辑组件，则存在脏写
    localStorage.setItem(OperationCache.CACHE_KEY, JSON.stringify(records))
  }

  /**
   * 开启同步任务
   */
  public static startSync = () => {
    console.log('start sync task...')
    if (!iWindow.SYNC_HANDLE) {
      iWindow.SYNC_HANDLE = setTimeout(() => {
        OperationCache.saveToServer()
        iWindow.SYNC_HANDLE = null
        OperationCache.startSync()
      }, OperationCache.SYNC_TIME)
    }
  }
}

export default OperationCache
